/*
 * Copyright (c) 2016 zhangcm. All Rights Reserved.
 */
package com.deram.ctin.common.utils;

import com.google.common.base.Preconditions;
import org.apache.commons.lang3.ArrayUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhangcm
 * @version 1.0, 2017/9/17
 */
public class CookieUtils {

    private CookieUtils(){}

    public static Cookie getCookie(HttpServletRequest request, String name) {
        Preconditions.checkNotNull(request);
        Cookie[] cookieArr = request.getCookies();
        return getCookie(cookieArr, name);
    }

    public static void setCookie(HttpServletResponse response, String name, String value) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    private static Cookie getCookie(Cookie[] cookieArr, String name){
        Preconditions.checkNotNull(name);
        if(ArrayUtils.isEmpty(cookieArr)){
            return null;
        }
        for (Cookie cookie : cookieArr) {
            if(name.equals(cookie.getName())){
                return cookie;
            }
        }
        return null;
    }
}
